package com.tanhua.admin.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lych.model.domain.Analysis;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 定时统计tb_log表中的数据，保存或更新tb_analysis表
     */
    public void analysis() throws ParseException {
        //定义查询日期
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString();
        //统计数据-注册数量
        Integer regCount = logMapper.queryWithTimeType("0102", today);
        //统计数据-登录数量
        Integer loginCount = logMapper.queryWithTimeType("0101", today);
        //统计数据-活跃数量
        Integer activeCount = logMapper.queryWithTime(today);
        //统计数据-次日留存数量
        Integer numRetenCount = logMapper.queryNumRetention1d(today, yesterday);
        //根据日期查询数据
        LambdaQueryWrapper<Analysis> lqw = new LambdaQueryWrapper<>();
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(today);
        lqw.eq(Analysis::getRecordDate,date);
        Analysis analysis = analysisMapper.selectOne(lqw);
        if(analysis == null) {
            //7、如果不存在，保存
            analysis = new Analysis();
            analysis.setRecordDate(date);
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetenCount);
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }else{
            //8、如果存在，更新
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetenCount);
            analysis.setUpdated(new Date());
            analysisMapper.updateById(analysis);
        }
    }
}
